package base.day03;


import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 描述：
 *      栈和队列之间的转换
 * @author hl
 * @version 1.0
 * @date 2020/10/25 16:02
 */
public class Code_04_StackAndQueueConvert {
    public static class TwoQueueStack<T>{
        public Queue<T> stack;
        public Queue<T> help;

        public TwoQueueStack() {
            stack = new LinkedList<>();
            help = new LinkedList<>();
        }
        public void push(T data){
            stack.add(data);
        }
        public T peek(){
            if (stack.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while(stack.size() > 1){
                help.add(stack.poll());
            }
            T res = stack.poll();
            help.add(res);
            swap();
            return res;
        }
        public T poll(){
            if (stack.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while(stack.size() > 1){
                help.add(stack.poll());
            }
            T res = stack.poll();
            swap();
            return res;
        }
        public void swap(){
            Queue<T> temp = stack;
            stack = help;
            help = temp;
        }

    }

    public static void main(String[] args) {
        TwoQueueStack<Integer> list = new TwoQueueStack<>();
        list.push(1);
        list.push(2);
        System.out.println(list.poll());
    }

    public class TwoStackQueue<T>{
        private Stack<T> stackPush;
        private Stack<T> stackPoll;

        public TwoStackQueue() {
            stackPush = new Stack<>();
            stackPoll = new Stack<>();
        }
        public void push(T data){
            stackPush.push(data);
        }
        public T poll(){
            if (stackPoll.isEmpty() && stackPush.isEmpty()) {
                throw new ArrayIndexOutOfBoundsException("栈为空");
            }
            if (stackPoll.isEmpty()) {
                while(!stackPush.isEmpty()){
                    stackPoll.push(stackPush.pop());
                }
            }
            return stackPoll.pop();
        }
        public T peek(){
            if (stackPoll.isEmpty() && stackPush.isEmpty()) {
                throw new ArrayIndexOutOfBoundsException("栈为空");
            }
            if (stackPoll.isEmpty()) {
                while(!stackPush.isEmpty()){
                    stackPoll.push(stackPush.pop());
                }
            }
            return stackPoll.peek();
        }
    }
}
